﻿using Newtonsoft.Json;
using SuperX.Common.Helper;
using SuperX.Common.Log;
using System;
using System.Collections.Generic;
using System.Text;

namespace SuperX.SuperSocket.Socket.Message
{
    public class XSocketMessage : ISsocketMessage
    {
        private byte[] _datas;
        private string _content;

        public Encoding DataFormat { get; set; } = Encoding.UTF8;

        public byte[] Datas
        {
            get { return _datas; }
            set
            {
                _datas = value;
                if (_datas != null)
                {
                    _content = DataFormat.GetString(_datas);
                }
            }
        }

        public string Content
        {
            get { return _content; }
            set
            {
                _content = value;
                if (_content != null)
                {
                    _datas = DataFormat.GetBytes(_content);
                }
            }
        }

        public XSocketMessage()
        {
        }

        public byte[] ConvertToBytes<T>(T obj) where T : new()
        {
            try
            {
                Content = JsonHelper.JsonSerialize(obj);
                return Datas;
            }
            catch (Exception ex)
            {
                Logger.ErrorException(ex);
                return null;
            }
        }

        public T GetObject<T>() where T : class, new()
        {
            try
            {
                return JsonHelper.JsonDeserialize<T>(Content);
            }
            catch (Exception ex)
            {
                Logger.Trace(Content);
                Logger.ErrorException(ex);
                return null;
            }
        }

        public const string ConnectedConst = "Welcome to SuperX-SuperSocket-Server";
        public const string ErrorConst = "Application error";
        public const string DisconnectedConst = "你已掉线!";
        public const string UnknowConst = "push Unknow request";
    }

    public class XSocketMessage<T> : XSocketMessage where T : new()
    {
        public XSocketMessage()
        {
        }

        public XSocketMessage(T obj)
        {
            ConvertToBytes(obj);
        }
    }
}